<template>
    <form @submit="login">
        <nut-cell class="flex justify-between items-center">
            <p>昵称</p>
            <input
                name="nickName"
                type="nickname"
                class="flex-1 h-8 text-right"
                placeholder="请输入昵称"
            />
        </nut-cell>
        <nut-cell class="flex justify-between items-center">
            <p>头像</p>
            <nut-avatar size="large" shape="round" class="overflow-hidden text-right">
                <img :src="avatar" />
            </nut-avatar>
            <button
                class="w-screnn h-16 opacity-0 absolute left-0 right-0"
                open-type="chooseAvatar"
                @chooseavatar="onChooseAvatar"
            ></button>
        </nut-cell>
        <view class="mt-8 w-screen flex flex-col">
            <nut-button type="primary" form-type="submit" class="self-center">点击登录</nut-button>
        </view>
    </form>
</template>

<script lang="ts" setup>
import Taro from '@tarojs/taro'
import { userLogin } from '@/api/user'
import { ref } from 'vue'
import { useAuth, setToken } from '@/config/auth'
import { apiConfig } from '@/api/request'
const { setUserInfo } = useAuth()
const avatar = ref(Taro.getStorageSync('avatar') || '')

const onChooseAvatar = (res) => {
    console.log(res)
    avatar.value = res.detail.avatarUrl

    Taro.uploadFile({
        url: `${apiConfig.API_BASE_URL}/carpark/upload.json`, //仅为示例，非真实的接口地址
        filePath: res.detail.avatarUrl,
        name: 'file',
        formData: {},
        success: (res) => {
            const { data } = JSON.parse(res.data)
            const { result } = data
            const { url } = result
            console.log('result', result)

            avatar.value = url
            Taro.setStorage({
                key: 'avatar',
                data: url
            })
        }
    })

    // 上传图片
    // Taro.uploadFile({
    //     url: '/route3001/upload', //仅为示例，非真实的接口地址
    //     filePath: e.detail.avatarUrl,
    //     name: 'file',
    //     formData: {},
    //     success: (res) => {
    //         const result = JSON.parse(res.data);
    //         const { url } = result.data;
    //         avatar.value = url;

    //         Taro.setStorage({
    //             key: 'avatar',
    //             data: url,
    //         });
    //     },
    // });
}

const login = async (form) => {
    const { nickName } = form.detail.value
    try {
        const { code } = await Taro.login()

        const {
            data: { token, userInfo }
        } = await userLogin({
            code,
            nickName,
            avatar: avatar.value
        })
        if (!token) {
            Taro.showToast({
                title: '登录失败',
                icon: 'success'
            })
            return
        }
        // 设置token
        setToken(token)
        setUserInfo(userInfo)

        Taro.showToast({
            title: '登录成功',
            icon: 'success'
        })

        setTimeout(() => {
            Taro.navigateBack()
        }, 500)
    } catch (error) {
        Taro.showToast({
            title: '登录失败,请重试',
            icon: 'error'
        })
        console.error('登录失败！' + error)
    }
}
</script>
